<template>
  <div class="page-container">
    <div class="page-header">
      <h2>运动记录</h2>
      <p>查看并管理您的运动活动记录</p>
    </div>
    
    <el-card class="filter-card">
      <div class="filter-container">
        <div class="filter-item">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            :shortcuts="dateShortcuts"
          />
        </div>
        <div class="filter-item">
          <el-select
            v-model="selectedTypeId"
            placeholder="选择运动类型"
            clearable
            style="width: 200px;"
          >
            <el-option
              v-for="type in exerciseTypes"
              :key="type.id"
              :label="type.name"
              :value="type.id"
            />
          </el-select>
        </div>
        <div class="filter-item">
          <el-button type="primary" @click="fetchExerciseRecords">
            <el-icon><Search /></el-icon>
            查询
          </el-button>
          <el-button @click="resetFilter">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
          <el-button type="success" @click="goToAddExerciseRecord">
            <el-icon><Plus /></el-icon>
            添加运动记录
          </el-button>
        </div>
      </div>
    </el-card>
    
    <el-card v-if="showStats" class="stats-card">
      <div class="stats-container">
        <div class="stat-item">
          <div class="stat-title">总运动时长</div>
          <div class="stat-value">{{ formatDuration(exerciseStats.totalDuration) }}</div>
        </div>
        <div class="stat-item">
          <div class="stat-title">总消耗卡路里</div>
          <div class="stat-value">{{ Math.round(exerciseStats.totalCalories || 0) }} kcal</div>
        </div>
        <div class="stat-item" v-if="dateRange && dateRange[0]">
          <div class="stat-title">选定时段内运动次数</div>
          <div class="stat-value">{{ exerciseRecords.length }} 次</div>
        </div>
      </div>
    </el-card>
    
    <el-card class="table-card">
      <el-table
        v-loading="loading"
        :data="exerciseRecords"
        style="width: 100%"
        border
        stripe
      >
        <el-table-column
          prop="startTime"
          label="开始时间"
          min-width="180"
        >
          <template #default="scope">
            <span v-if="scope.row.startTime">{{ formatDateTime(scope.row, 'startTime') }}</span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="exerciseType.name"
          label="运动类型"
          min-width="120"
        />
        <el-table-column
          prop="durationMinutes"
          label="时长"
          min-width="100"
        >
          <template #default="scope">
            {{ formatDuration(scope.row.durationMinutes) }}
          </template>
        </el-table-column>
        <el-table-column
          prop="intensity"
          label="强度"
          min-width="100"
        >
          <template #default="scope">
            <el-tag :type="getIntensityTagType(scope.row.intensity)">
              {{ getIntensityDisplayName(scope.row.intensity) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="caloriesBurned"
          label="消耗卡路里"
          min-width="120"
        >
          <template #default="scope">
            {{ Math.round(scope.row.caloriesBurned) }} kcal
          </template>
        </el-table-column>
        <el-table-column
          prop="location"
          label="地点"
          min-width="120"
        />
        <el-table-column
          label="操作"
          width="150"
          fixed="right"
        >
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              circle
              @click="handleView(scope.row)"
            >
              <el-icon><View /></el-icon>
            </el-button>
            <el-button
              type="danger"
              size="small"
              circle
              @click="handleDelete(scope.row)"
            >
              <el-icon><Delete /></el-icon>
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container" v-if="!isFilterMode">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
      
      <el-empty v-if="exerciseRecords.length === 0" description="暂无运动记录" />
    </el-card>
    
    <!-- 详情对话框 -->
    <el-dialog
      v-model="detailsVisible"
      title="运动详情"
      width="600px"
    >
      <div v-if="currentRecord" class="record-details">
        <div class="detail-item">
          <div class="label">运动类型:</div>
          <div class="value">{{ currentRecord.exerciseType?.name }}</div>
        </div>
        <div class="detail-item">
          <div class="label">开始时间:</div>
          <div class="value">{{ currentRecord.startTime ? formatDateTime(currentRecord, 'startTime') : '-' }}</div>
        </div>
        <div class="detail-item" v-if="currentRecord.endTime">
          <div class="label">结束时间:</div>
          <div class="value">{{ formatDateTime(currentRecord, 'endTime') }}</div>
        </div>
        <div class="detail-item">
          <div class="label">持续时间:</div>
          <div class="value">{{ formatDuration(currentRecord.durationMinutes) }}</div>
        </div>
        <div class="detail-item">
          <div class="label">强度:</div>
          <div class="value">
            <el-tag :type="getIntensityTagType(currentRecord.intensity)">
              {{ getIntensityDisplayName(currentRecord.intensity) }}
            </el-tag>
          </div>
        </div>
        <div class="detail-item">
          <div class="label">消耗卡路里:</div>
          <div class="value">{{ Math.round(currentRecord.caloriesBurned) }} kcal</div>
        </div>
        <div class="detail-item" v-if="currentRecord.location">
          <div class="label">地点:</div>
          <div class="value">{{ currentRecord.location }}</div>
        </div>
        <div class="detail-item notes" v-if="currentRecord.notes">
          <div class="label">备注:</div>
          <div class="value">{{ currentRecord.notes }}</div>
        </div>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailsVisible = false">关闭</el-button>
          <el-button type="primary" @click="handleEdit(currentRecord)">
            编辑
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getPagedExerciseRecords,
  getExerciseRecordsByDateRange,
  getExerciseRecordsByType,
  getExerciseStats,
  getExerciseStatsByDateRange,
  deleteExerciseRecord
} from '@/api/exerciseRecord'
import { getAllExerciseTypes } from '@/api/exerciseType'

const router = useRouter()
const loading = ref(false)
const exerciseRecords = ref([])
const exerciseTypes = ref([])
const exerciseStats = ref({
  totalDuration: 0,
  totalCalories: 0
})
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const dateRange = ref(null)
const selectedTypeId = ref(null)
const isFilterMode = ref(false)
const detailsVisible = ref(false)
const currentRecord = ref(null)

// 日期快捷选项
const dateShortcuts = [
  {
    text: '最近一周',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      return [start, end]
    }
  },
  {
    text: '最近一个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      return [start, end]
    }
  },
  {
    text: '最近三个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
      return [start, end]
    }
  }
]

const showStats = computed(() => {
  return exerciseStats.value && (exerciseStats.value.totalDuration || exerciseStats.value.totalCalories)
})

// 获取运动记录
const fetchExerciseRecords = async () => {
  loading.value = true
  
  try {
    let records = [];
    
    // 根据筛选条件获取数据
    if (dateRange.value && dateRange.value[0] && dateRange.value[1]) {
      // 日期范围筛选
      const startDate = new Date(dateRange.value[0])
      startDate.setHours(0, 0, 0, 0)
      
      const endDate = new Date(dateRange.value[1])
      endDate.setHours(23, 59, 59, 999)
      
      // 将日期转换为yyyy-MM-dd HH:mm:ss格式，避免ISO格式的时区问题
      const formatDateString = (date) => {
        return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}:${String(date.getSeconds()).padStart(2, '0')}`
      }

      const formattedStartDate = formatDateString(startDate);
      const formattedEndDate = formatDateString(endDate);

      console.log('查询日期范围:', {
        开始: formattedStartDate,
        结束: formattedEndDate
      });
      
      if (selectedTypeId.value) {
        // 日期范围 + 运动类型
        records = await getExerciseRecordsByDateRange(
          formattedStartDate,
          formattedEndDate
        )
        exerciseRecords.value = records.filter(record => 
          record.exerciseType && record.exerciseType.id === selectedTypeId.value
        )
      } else {
        // 仅日期范围
        exerciseRecords.value = await getExerciseRecordsByDateRange(
          formattedStartDate,
          formattedEndDate
        )
        records = exerciseRecords.value;
      }
      
      // 前端计算统计数据，不再调用后端统计API
      calculateStatsFromRecords(exerciseRecords.value);
      
      total.value = exerciseRecords.value.length
      isFilterMode.value = true
    } else if (selectedTypeId.value) {
      // 仅运动类型筛选
      exerciseRecords.value = await getExerciseRecordsByType(selectedTypeId.value)
      records = exerciseRecords.value;
      total.value = exerciseRecords.value.length
      isFilterMode.value = true
      
      // 前端计算统计数据
      calculateStatsFromRecords(exerciseRecords.value);
    } else {
      // 无筛选，使用分页
      const response = await getPagedExerciseRecords({
        page: currentPage.value - 1,
        size: pageSize.value,
        sort: 'startTime,desc'
      })
      
      exerciseRecords.value = response.content
      records = response.content;
      total.value = response.totalElements
      isFilterMode.value = false
      
      try {
        // 尝试获取总体统计信息，失败时在前端计算
        const stats = await getExerciseStats()
        exerciseStats.value = stats
      } catch (error) {
        console.warn('获取总体统计失败，使用前端计算:', error);
        calculateStatsFromRecords(exerciseRecords.value);
      }
    }
    
    // 检查获取到的记录
    if (records.length > 0) {
      console.log('获取的运动记录示例:', {
        第一条记录: records[0],
        开始时间: records[0].startTime,
        开始时间类型: typeof records[0].startTime,
        结束时间: records[0].endTime,
        时长: records[0].durationMinutes
      });
    } else {
      console.log('没有获取到运动记录');
    }
  } catch (error) {
    console.error('获取运动记录失败:', error)
    ElMessage.error('获取运动记录失败')
  } finally {
    loading.value = false
  }
}

// 在前端计算统计数据
const calculateStatsFromRecords = (records) => {
  if (!records || records.length === 0) {
    exerciseStats.value = {
      totalRecords: 0,
      totalDuration: 0,
      totalCalories: 0,
      avgDuration: 0,
      avgCalories: 0
    };
    return;
  }
  
  // 计算总运动时长和卡路里
  let totalDuration = 0;
  let totalCalories = 0;
  const typeMap = new Map(); // 记录运动类型频率
  const intensityCount = {
    LOW: 0,
    MEDIUM: 0,
    HIGH: 0,
    VERY_HIGH: 0
  };
  
  for (const record of records) {
    // 累加时长
    if (record.durationMinutes) {
      totalDuration += record.durationMinutes;
    }
    
    // 累加卡路里
    if (record.caloriesBurned) {
      totalCalories += record.caloriesBurned;
    }
    
    // 统计运动类型
    if (record.exerciseType && record.exerciseType.id) {
      const typeId = record.exerciseType.id;
      const typeName = record.exerciseType.name;
      const typeCount = typeMap.get(typeId) || { id: typeId, name: typeName, count: 0 };
      typeCount.count += 1;
      typeMap.set(typeId, typeCount);
    }
    
    // 统计强度分布
    if (record.intensity && intensityCount[record.intensity] !== undefined) {
      intensityCount[record.intensity] += 1;
    }
  }
  
  // 转换运动类型Map为数组并排序
  const frequentTypes = Array.from(typeMap.values())
    .sort((a, b) => b.count - a.count)
    .slice(0, 3); // 取前3个
  
  exerciseStats.value = {
    totalRecords: records.length,
    totalDuration: totalDuration,
    totalCalories: totalCalories,
    avgDuration: Math.round(totalDuration / records.length) || 0,
    avgCalories: Math.round(totalCalories / records.length) || 0,
    frequentTypes: frequentTypes,
    intensityDistribution: intensityCount
  };
  
  console.log('前端计算的统计数据:', exerciseStats.value);
}

// 获取运动类型
const fetchExerciseTypes = async () => {
  try {
    exerciseTypes.value = await getAllExerciseTypes()
  } catch (error) {
    console.error('获取运动类型失败:', error)
    ElMessage.error('获取运动类型失败')
  }
}

const handleSizeChange = (size) => {
  pageSize.value = size
  fetchExerciseRecords()
}

const handleCurrentChange = (page) => {
  currentPage.value = page
  fetchExerciseRecords()
}

const resetFilter = () => {
  dateRange.value = null
  selectedTypeId.value = null
  currentPage.value = 1
  isFilterMode.value = false
  fetchExerciseRecords()
}

const formatDateTime = (row, columnName = 'startTime') => {
  if (!row) return '-';
  
  const dateValue = row[columnName];
  if (!dateValue) return '-';
  
  try {
    console.log('格式化日期:', columnName, dateValue, typeof dateValue);
    
    let date;
    
    // 处理不同格式的日期
    if (typeof dateValue === 'string') {
      if (dateValue.includes(' ')) {
        // 处理格式如 "2025-04-09 13:19:10.000000"
        const isoString = dateValue.replace(' ', 'T');
        date = new Date(isoString);
      } else if (dateValue.includes('T')) {
        // 处理ISO格式 "2025-04-09T13:19:10.000Z" 或 "2025-04-09T13:19:10"
        date = new Date(dateValue);
      } else {
        // 处理简单日期格式 "2025-04-09"
        const parts = dateValue.split('-');
        if (parts.length === 3) {
          date = new Date(parts[0], parts[1]-1, parts[2]);
        } else {
          date = new Date(dateValue);
        }
      }
    } else if (dateValue instanceof Date) {
      date = dateValue;
    } else {
      console.error('未知的日期类型:', typeof dateValue, dateValue);
      return dateValue.toString();
    }
    
    if (isNaN(date.getTime())) {
      console.error('无效的日期:', dateValue);
      return String(dateValue);
    }
    
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
  } catch (error) {
    console.error('日期格式化错误:', error, dateValue);
    return String(dateValue);
  }
}

const formatDuration = (minutes) => {
  if (!minutes) return '0分钟'
  if (minutes < 60) return `${minutes}分钟`
  
  const hours = Math.floor(minutes / 60)
  const remainingMinutes = minutes % 60
  
  if (remainingMinutes === 0) return `${hours}小时`
  return `${hours}小时${remainingMinutes}分钟`
}

const getIntensityDisplayName = (intensity) => {
  const intensityMap = {
    'LOW': '低强度',
    'MEDIUM': '中等强度',
    'HIGH': '高强度',
    'VERY_HIGH': '极高强度'
  }
  return intensityMap[intensity] || intensity
}

const getIntensityTagType = (intensity) => {
  const typeMap = {
    'LOW': 'success',
    'MEDIUM': 'info',
    'HIGH': 'warning',
    'VERY_HIGH': 'danger'
  }
  return typeMap[intensity] || ''
}

const handleView = (record) => {
  currentRecord.value = record
  detailsVisible.value = true
}

const handleEdit = (record) => {
  detailsVisible.value = false
  
  // 在跳转前先保存当前记录到本地存储，以便编辑页面直接使用
  try {
    // 深复制对象并去除可能的循环引用
    const recordCopy = JSON.parse(JSON.stringify({
      id: record.id,
      exerciseType: record.exerciseType ? {
        id: record.exerciseType.id,
        name: record.exerciseType.name
      } : null,
      startTime: record.startTime,
      endTime: record.endTime,
      durationMinutes: record.durationMinutes,
      intensity: record.intensity,
      location: record.location || '',
      notes: record.notes || '',
      caloriesBurned: record.caloriesBurned
    }));
    
    // 保存到sessionStorage
    sessionStorage.setItem('currentExerciseRecord', JSON.stringify(recordCopy));
    console.log('已保存当前记录到会话存储:', recordCopy);
  } catch (error) {
    console.error('保存记录到会话存储失败:', error);
  }
  
  router.push(`/exercise-records/edit/${record.id}`);
}

const handleDelete = (record) => {
  ElMessageBox.confirm(
    '确定要删除该运动记录吗？删除后无法恢复。',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await deleteExerciseRecord(record.id)
      ElMessage.success('删除成功')
      fetchExerciseRecords()
    } catch (error) {
      console.error('删除运动记录失败:', error)
      ElMessage.error('删除运动记录失败')
    }
  }).catch(() => {})
}

const goToAddExerciseRecord = () => {
  router.push('/exercise-records/add')
}

onMounted(() => {
  fetchExerciseTypes()
  fetchExerciseRecords()
})
</script>

<style scoped>
.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0 0 10px 0;
  font-weight: 500;
}

.page-header p {
  margin: 0;
  color: #606266;
  font-size: 14px;
}

.filter-card {
  margin-bottom: 20px;
}

.filter-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
}

.filter-item {
  margin-bottom: 10px;
}

.stats-card {
  margin-bottom: 20px;
}

.stats-container {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}

.stat-item {
  flex: 1;
  min-width: 200px;
  text-align: center;
  padding: 15px;
  border-right: 1px solid #ebeef5;
}

.stat-item:last-child {
  border-right: none;
}

.stat-title {
  font-size: 14px;
  color: #606266;
  margin-bottom: 10px;
}

.stat-value {
  font-size: 24px;
  color: #303133;
  font-weight: bold;
}

.table-card {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.record-details {
  padding: 10px;
}

.detail-item {
  display: flex;
  margin-bottom: 15px;
}

.detail-item .label {
  width: 120px;
  color: #606266;
  font-weight: bold;
}

.detail-item .value {
  flex: 1;
}

.detail-item.notes {
  display: block;
}

.detail-item.notes .label {
  margin-bottom: 8px;
}

.detail-item.notes .value {
  padding: 10px;
  background-color: #f8f8f8;
  border-radius: 4px;
  min-height: 60px;
}

@media (max-width: 768px) {
  .filter-container {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .filter-item {
    width: 100%;
    margin-bottom: 10px;
  }
  
  .stats-container {
    flex-direction: column;
  }
  
  .stat-item {
    border-right: none;
    border-bottom: 1px solid #ebeef5;
  }
  
  .stat-item:last-child {
    border-bottom: none;
  }
  
  .detail-item {
    flex-direction: column;
  }
  
  .detail-item .label {
    width: 100%;
    margin-bottom: 5px;
  }
}
</style>